﻿using System.Collections.Generic;
using Ymatou.User.Dto.Auth;
using YmtAuth.Domain.Model.Safe;
using YmtAuth.Domain.Repository;
using YmtAuth.Dto;
using YmtSystem.CrossCutting;
using System.Linq;
using System;
using ServiceStack;
using YmtAuth.Domain;

namespace YmtAuth.AppService
{
    /// <summary>
    /// 查询、设置双重验证
    /// </summary>
    public class DualSecurityAppService : IDualSecurityAppService
    {
        private static readonly IDualSecurityRepository dualSecurityRepo = LocalServiceLocator.GetService<IDualSecurityRepository>();
        private static ISecurityQuestionRepository securityQuestionRepo { get { return LocalServiceLocator.GetService<ISecurityQuestionRepository>(); } }

        public ResponseData<bool> GetDualSecurityResult(GetDualSecurityResultRequestDto dto)
        {
            //参数检查
            YmtSystemAssert.AssertArgumentNotNull(dto, "无效的GetDualSecurityResultRequestDto");
            ResponseData<bool> res = null;

            int userId = dto.UserId;
            if (userId <= 0) res = ResponseData<bool>.Create(false, false, "用户ID非法", "100");
            else
            {
                DualSecurity dualSecurity = dualSecurityRepo.GetDualSecurityResult(userId);

                if (dualSecurity == null)
                {
                    res = ResponseData<bool>.Create(false, true, "用户未设置过双重验证", "400");
                }
                else
                {
                    res = ResponseData<bool>.Create(dualSecurity.Enable, true, "ok", "200");
                }
            }

            return res;
        }

        public ResponseData<bool> SetDualSecurity(SetDualSecurityRequestDto dto)
        {
            //参数检查
            YmtSystemAssert.AssertArgumentNotNull(dto, "无效的SetDualSecurityRequestDto");
            if (!dto.Enable.HasValue) return ResponseData<bool>.Create(false, false, "Enable参数不能为空", "100");

            ResponseData<bool> res = null;
            int userId = dto.UserId;
            if (userId <= 0) res = ResponseData<bool>.Create(false, false, "用户ID非法", "100");
            else
            {
                //查询用户是否设置安全问题
                List<UserSecurityQuestion> userSecurityQuestionList = securityQuestionRepo.GetUserSecurityQuestion(userId);

                if (userSecurityQuestionList.Any())
                {
                    res = dualSecurityRepo.SetDualSecurity(userId, dto.Enable.Value);
                }
                else
                {
                    YmatouLoggingService.Debug("[SetDualSecurity] user {0} hasn't set security question", userId);

                    res = ResponseData<bool>.Create(false, true, "请先设置用户安全问题", "300");
                }
            }

            return res;
        }
    }
}
